import axios from "axios";
import { storageLocal } from "/@/utils/storage";
import NotifMessage from "/@/utils/message/notification";
import router from "/@/router/index";
// import { downloadFile } from "../ecm";

// interface fileType {
//   fileName: string;
//   fileSize: number;
//   fileType: string;
//   uuidFile: string;
// }

// interface pdfFileType {
//   contractInfoId: string;
//   flowId: string;
//   instanceId: string;
// }

const baseUrl = import.meta.env.VITE_BASE_URL;

export const download = (fileInfo): void => {
  if (!fileInfo) return;
  if (fileInfo.uuidFile.indexOf("gns") !== -1) {
    window.open(
      `${location.origin}${location.pathname}#/preview?uuidFile=${fileInfo.uuidFile}&fileName=${fileInfo.name}`
    );
    // downloadFile(fileInfo.uuidFile, fileInfo.name);
    return;
  }

  let authorization = "";

  if (storageLocal.getItem("info")) {
    authorization = storageLocal.getItem("info")?.accessToken;
  }
  let downloadUrl = `/snow-admin/common/file/download`;

  if (import.meta.env.MODE === "production") {
    downloadUrl = `${baseUrl}/snow-admin/common/file/download`;
  }

  console.log(import.meta.env.MODE, "mode", downloadUrl);

  const formData = { uuidFile: fileInfo?.uuidFile };
  axios({
    method: "get",
    url: downloadUrl,
    params: formData,
    responseType: "blob",
    headers: {
      Authorization: authorization,
      loginMethod: "PC"
    }
  })
    .then(res => {
      const data = res.data;
      // @ts-ignore
      const url = window.URL.createObjectURL(new Blob([data]));
      const a = document.createElement("a");
      a.style.display = "none";
      a.href = url;
      // a.setAttribute("download", `${fileInfo.uuidFile}${fileInfo.fileType}`);
      a.setAttribute("download", `${fileInfo.fileName}`);
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(a.href);
      document.body.removeChild(a);
    })
    .catch(err => {
      if (err.response) {
        if (err.response.status === 500) {
          NotifMessage.error("您没有该操作权限");
        } else if (err?.response?.status === 403) {
          NotifMessage.error("登录失效，请重新登录");
          router.replace("/login");
        }
      } else if (err.request) {
        console.log(err.request);
      } else {
        console.log("err", err.message);
      }
    });
};

export const previewImage = async fileInfo => {
  let authorization = "";

  if (storageLocal.getItem("info")) {
    authorization = storageLocal.getItem("info")?.accessToken;
  }
  let downloadUrl = `/snow-admin/common/file/download`;

  if (import.meta.env.MODE === "production") {
    downloadUrl = `${baseUrl}/snow-admin/common/file/download`;
  }

  console.log(import.meta.env.MODE, "mode", downloadUrl);

  const formData = { uuidFile: fileInfo?.uuidFile };
  const res = await axios({
    method: "get",
    url: downloadUrl,
    params: formData,
    responseType: "blob",
    headers: {
      Authorization: authorization,
      loginMethod: "PC"
    }
  });

  const data = res.data;
  // @ts-ignore
  const url = window.URL.createObjectURL(new Blob([data]));
  return url;
};

export const viewpdf = (fileInfo: any, type: string): void => {
  if (!fileInfo) return;
  let authorization = "";
  if (storageLocal.getItem("info")) {
    authorization = storageLocal.getItem("info")?.accessToken;
  }

  let downloadUrl = "";
  if (type === "arrival") {
    downloadUrl = "/snow-admin/arrivedAcceptance/downloadAcc";
  } else if (type === "common") {
    downloadUrl = `/snow-admin/flowForm/downloadAcc/${fileInfo.contractInfoId}`;
  } else if (type === "quality") {
    downloadUrl = `/snow-admin/qtyCheck/downloadQty/${fileInfo.contractInfoId}`;
  }

  if (import.meta.env.MODE === "production") {
    downloadUrl = `${baseUrl}${downloadUrl}`;
  }

  const formData = fileInfo;
  axios({
    method: "post",
    url: downloadUrl,
    data: formData,
    responseType: "blob",
    headers: {
      Authorization: authorization
    }
  })
    .then(res => {
      const data = res.data;
      // @ts-ignore
      const url = window.URL.createObjectURL(new Blob([data]));
      const fileUrl = encodeURIComponent(url);
      // console.log(window, "window", fileUrl);
      window.open(
        `${window.location.origin}${
          import.meta.env.VITE_PUBLIC_PATH
        }pdfjs/web/viewer.html?file=${fileUrl}`,
        "_blank"
      );
    })
    .catch(err => {
      if (err.response) {
        if (err.response.status === 500) {
          NotifMessage.error("您没有该操作权限");
        } else if (err?.response?.status === 403) {
          NotifMessage.error("登录失效，请重新登录");
          router.replace("/login");
        }
      } else if (err.request) {
        console.log(err.request);
      } else {
        console.log("err", err.message);
      }
    });
};

/**
 *
 * @param fileInfo
 * @param type
 */
export const downloadpdf = (fileInfo: any, type: string): void => {
  if (!fileInfo) return;
  let authorization = "";
  if (storageLocal.getItem("info")) {
    authorization = storageLocal.getItem("info")?.accessToken;
  }
  let downloadUrl = "";

  if (type === "arrival") {
    downloadUrl = "/snow-admin/arrivedAcceptance/downloadAcc";
  } else if (type === "common") {
    downloadUrl = `/snow-admin/flowForm/downloadAcc/${fileInfo.contractInfoId}`;
  } else if (type === "quality") {
    downloadUrl = `/snow-admin/qtyCheck/downloadQty/${fileInfo.contractInfoId}`;
  }

  if (import.meta.env.MODE === "production") {
    downloadUrl = `${baseUrl}${downloadUrl}`;
  }

  const formData = {
    contractInfoId: fileInfo.contractInfoId,
    flowId: fileInfo.flowId,
    instanceId: fileInfo.instanceId
  };
  axios({
    method: "post",
    url: downloadUrl,
    data: formData,
    responseType: "blob",
    headers: {
      Authorization: authorization
    }
  })
    .then(res => {
      const data = res.data;
      // @ts-ignore
      const url = window.URL.createObjectURL(new Blob([data]));
      const a = document.createElement("a");
      a.style.display = "none";
      a.href = url;
      // a.setAttribute("download", `${fileInfo.uuidFile}${fileInfo.fileType}`);
      a.setAttribute("download", `${fileInfo.pdfName}.pdf`);
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(a.href);
      document.body.removeChild(a);
    })
    .catch(err => {
      if (err.response) {
        if (err.response.status === 500) {
          NotifMessage.error("您没有该操作权限");
        } else if (err?.response?.status === 403) {
          NotifMessage.error("登录失效，请重新登录");
          router.replace("/login");
        }
      } else if (err.request) {
        console.log(err.request);
      } else {
        console.log("err", err.message);
      }
    });
};

export const downloadXml = (fileInfo): void => {
  if (!fileInfo) return;
  let authorization = "";
  if (storageLocal.getItem("info")) {
    authorization = storageLocal.getItem("info")?.accessToken;
  }
  let downloadUrl = `/snow-admin/flowProjectProgress/export/xml`;

  if (import.meta.env.MODE === "production") {
    downloadUrl = `${baseUrl}/snow-admin/flowProjectProgress/export/xml`;
  }

  const formData = {
    ganttJsonStr: fileInfo.ganttJsonStr,
    fileName: fileInfo.fileName
  };

  axios({
    method: "post",
    url: downloadUrl,
    data: formData,
    responseType: "blob",
    headers: {
      Authorization: authorization
    }
  })
    .then(res => {
      const data = res.data;
      // @ts-ignore
      const url = window.URL.createObjectURL(new Blob([data]));
      const a = document.createElement("a");
      a.style.display = "none";
      a.href = url;
      // a.setAttribute("download", `${fileInfo.uuidFile}${fileInfo.fileType}`);
      a.setAttribute("download", `${fileInfo.fileName}`);
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(a.href);
      document.body.removeChild(a);
    })
    .catch(err => {
      if (err.response) {
        if (err.response.status === 500) {
          NotifMessage.error("您没有该操作权限");
        } else if (err?.response?.status === 403) {
          NotifMessage.error("登录失效，请重新登录");
          router.replace("/login");
        }
      } else if (err.request) {
        console.log(err.request);
      } else {
        console.log("err", err.message);
      }
    });
};

export const postDocumentDownload = (fileInfo, url): void => {
  if (!fileInfo) return;
  let authorization = "";
  if (storageLocal.getItem("info")) {
    authorization = storageLocal.getItem("info")?.accessToken;
  }
  let downloadUrl = url;
  if (import.meta.env.MODE === "production") {
    downloadUrl = `${baseUrl}` + url;
  }
  const formData = {
    zipDownloadDTOList: fileInfo
  };
  axios({
    method: "post",
    url: downloadUrl,
    data: formData,
    responseType: "blob",
    headers: {
      Authorization: authorization
    }
  })
    .then(res => {
      const data = res.data;
      let filename = res.headers; //下载后文件名
      filename = filename["content-disposition"];
      filename =
        filename?.split(";")[1]?.split("filename=")[1] ??
        `${new Date().getTime()}.zip`;

      // @ts-ignore
      const url = window.URL.createObjectURL(new Blob([data]));
      const a = document.createElement("a");
      a.style.display = "none";
      a.href = url;
      // a.setAttribute("download", `${fileInfo.uuidFile}${fileInfo.fileType}`);
      a.setAttribute("download", `${filename}`);
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(a.href);
      document.body.removeChild(a);
    })
    .catch(err => {
      if (err.response) {
        if (err.response.status === 500) {
          NotifMessage.error("您没有该操作权限");
        } else if (err?.response?.status === 403) {
          NotifMessage.error("登录失效，请重新登录");
          router.replace("/login");
        }
      } else if (err.request) {
        console.log(err.request);
      } else {
        console.log("err", err.message);
      }
    });
};
